<template>
  <div class="app-container ad-class">
    <el-row style="margin-bottom:10px">
      <el-col :span="3">
        <el-input v-model="search.keyword" placeholder="Keyword" style="width:95%" />
      </el-col>
      <el-col :span="4">
        <el-select ref="ap_select" v-model="search.ap_id" placeholder="Please Choose Ad Slot" style="width:95%" no-data-text="Can't find record">
          <el-option
            v-for="item in apList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="search.ap_enabled" clearable placeholder="Please Choose Enable Status" style="width:95%" no-data-text="Can't find record">
          <el-option label="All" :value="0" />
          <el-option label="Active" :value="1" />
          <el-option label="Inactive" :value="2" />
        </el-select>
      </el-col>
      <el-button type="primary" icon="el-icon-search" @click="gettableinto" />
      <el-button type="primary" @click="handleAddRole">Add</el-button>
    </el-row>
    <el-table
      :data="tableList"
      style="width: 100%;margin-top:30px;"
      :empty-text="empty_text"
      border
    >
      <el-table-column align="center" prop="id" label="ID" width="50">
        <template slot-scope="scope">{{ scope.row.adv_id }}</template>
      </el-table-column>
      <el-table-column align="center" label="Ad name">
        <template slot-scope="scope">{{ scope.row.adv_title }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Sort pictures" width="110">
        <template slot-scope="scope">{{ scope.row.adv_sort }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Hits" width="80">
        <template slot-scope="scope">{{ scope.row.adv_clicknum }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Image" width="180">
        <template slot-scope="scope">
          <el-image
            :src="baseUrl.replace('/api/', '') + scope.row.adv_image"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="Enable" width="80">
        <template slot-scope="scope"><el-checkbox :value="scope.row.adv_enabled===1" @change="changeEnableStatus(scope)" /></template>
      </el-table-column>
      <el-table-column align="header-center" label="Starting Time" width="160">
        <template slot-scope="scope">{{ scope.row.adv_startdate }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="End Time" width="160">
        <template slot-scope="scope">{{ scope.row.adv_enddate }}</template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="100">
        <template slot-scope="scope">
          <el-row>
            <el-col :span="8">
              <el-link class="el-icon-edit icon-class" @click="handleEdit(scope)" />
            </el-col>
            <el-col :span="8">
              <el-link class="el-icon-delete icon-class" @click="handleDelete(scope)" />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? 'Edit Advertising' : 'New Advertising'"
    >
      <div style="margin:0 30px">
        <el-form ref="connectForm" :model="ad_info" :rules="rules" label-width="150px" label-position="left">
          <el-form-item label="Ad name" prop="adv_title">
            <el-input v-model="ad_info.adv_title" placeholder="Ad name" />
          </el-form-item>
          <el-form-item label="Ad Slot" prop="ap_id">
            <el-select v-model="ad_info.ap_id" placeholder="Please Choose" no-data-text="Can't find record" style="width:50%">
              <el-option
                v-for="item in apList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Starting Time" prop="adv_startdate">
            <el-date-picker v-model="ad_info.adv_startdate" type="datetime" placeholder="Starting Time" />
          </el-form-item>
          <el-form-item label="End Time" prop="adv_enddate">
            <el-date-picker v-model="ad_info.adv_enddate" type="datetime" placeholder="End Time" />
          </el-form-item>
          <el-form-item label="Sort pictures" prop="adv_sort">
            <el-input v-model="ad_info.adv_sort" type="number" placeholder="Sort pictures" />
          </el-form-item>
          <el-form-item label="Enabled">
            <el-checkbox v-model="ad_info.adv_enabled" />
          </el-form-item>
          <el-form-item label="Upload Picture">
            <el-upload
              class="upload-demo"
              :action="baseUrl + 'user/data/upload.html'"
              :headers="{
                'XX-Token': tokenData,
                'XX-Device-Type': 'pc',
              }"
              :data="{key: 'file'}"
              :on-preview="handlePreview"
              accept=".gif,.jpg,.jpeg,.png"
              :file-list="fileList"
              :before-upload="uploadChange"
              :on-success="uploadImageSuccess"
            >
              <el-row>
                <el-col :span="12">
                  <el-input readonly />
                </el-col>
                <el-col :span="4">
                  <el-button size="small" type="primary">Browse</el-button>
                </el-col>
              </el-row>
              <!-- <div class="el-upload__tip">The image formats supported by the system are: gif, jpg, jpeg, png</div> -->
            </el-upload>
          </el-form-item>
          <el-form-item label="Background Color" prop="adv_bgcolor">
            <el-color-picker v-model="ad_info.adv_bgcolor" />
          </el-form-item>
          <el-form-item label="Width" prop="desc">
            <el-input v-model="ad_info.adv_width" placeholder="Width" />
          </el-form-item>
          <el-form-item label="Height" prop="desc">
            <el-input v-model="ad_info.adv_height" placeholder="Height" />
          </el-form-item>
          <el-form-item label="Link Address" prop="adv_link">
            <el-input v-model="ad_info.adv_link" placeholder="Link Address" />
          </el-form-item>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirm">Confirm</el-button>
        </div>
      </div>
    </el-dialog>
    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="slot,prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    >
      <span class="el-pagination__total">Total {{ totalpage }}</span>
    </el-pagination>
  </div>
</template>

<script>
// import MyTest from './noets.vue'
import {
  getList,
  getdictionary,
  save,
  del,
  getDetails
} from '@/api/advertising/ad'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth' // get token from cookie

const defaultInfo = {
  adv_id: '',
  ap_id: '',
  adv_title: '',
  adv_link: '',
  adv_image: '',
  adv_startdate: '',
  adv_enddate: '',
  adv_sort: '',
  adv_enabled: false,
  adv_bgcolor: '',
  adv_width: '',
  adv_height: ''
}

export default {
  components: {
    // MyTest
  },
  data() {
    return {
      ap_id: '',
      ad_info: {
        adv_id: '',
        ap_id: '',
        adv_title: '',
        adv_link: '',
        adv_image: '',
        adv_startdate: '',
        adv_enddate: '',
        adv_sort: '',
        adv_enabled: false,
        adv_bgcolor: '',
        adv_width: '',
        adv_height: ''
      },
      search: {
        keyword: '',
        ap_id: '',
        ap_enabled: '',
        page: 1,
        per_page: 10
      },
      empty_text: '',
      totalpage: 0,
      tableList: [],
      apList: [],
      fileList: [],
      dialogVisible: false,
      dialogType: 'new',
      tokenData: '',
      rules: {
        adv_title: [{ required: true, message: 'Please enter a Ad Name', trigger: 'blur' }],
        ap_id: [{ required: true, message: 'Please enter a Ad Postion' }]
      }
    }
  },
  computed: {
    baseUrl() {
      return process.env.VUE_APP_BASE_API
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      this.ad_info = Object.assign({}, defaultInfo)
      if (this.$refs['connectForm']) this.$refs['connectForm'].clearValidate()

      if (!newValue) {
        this.fileList = []
      }
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    if (this.$route.query && this.$route.query.ap_id) {
      // 业务逻辑
      this.ap_id = this.$route.query.ap_id
    }
    this.getTableData()
    this.conToken()
    this.getApList()
  },
  methods: {
    async conToken() {
      this.tokenData = getToken()
    },
    handlePreview(file) {
      console.log(file)
      console.log(this.fileList)
    },
    uploadChange(file) {
      if (window.createObjectURL !== undefined) {
        console.log(window.createObjectURL(file))
      } else if (window.URL !== undefined) {
        console.log(window.URL.createObjectURL(file))
      } else if (window.webkitURL !== undefined) {
        console.log(window.webkitURL.createObjectURL(file))
      }
    },
    uploadImageSuccess(response, file, fileList) {
      this.ad_info.adv_image = response.data.url
    },
    handleIndexChange(index) {
      this.search.page = index
      this.getTableData()
    },
    gettableinto() {
      this.keyword = this.keywords
      this.getTableData()
    },
    async getTableData() {
      this.empty_text = 'Loading ......'
      await getList(this.search).then(response => {
        this.tableList = response.data
        this.totalpage = response.total
        this.per_page = response.per_page
        this.current_page = response.current_page
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.tableList = []
        this.empty_text = 'Can\'t find record in table'
      })
    },
    getApList() {
      getdictionary({ dict_type: 'adv_pos' }).then(res => {
        this.search.ap_id = this.ap_id
        this.apList = res
      })
    },
    handleAddRole() {
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      await getDetails({ adv_id: scope.row.adv_id }).then(async result => {
        this.ad_info = result
        this.ad_info.adv_enabled = result.adv_enabled > 0
      })
    },
    changeEnableStatus(scope) {
      const data = Object.assign({}, scope.row)
      if (scope.row.adv_startdate) {
        data.adv_startdate = parseTime(scope.row.adv_startdate, '{y}-{m}-{d}  {h}:{i}:{s}')
      }
      if (scope.row.adv_enddate) {
        data.adv_enddate = parseTime(scope.row.adv_enddate, '{y}-{m}-{d}  {h}:{i}:{s}')
      }
      data.adv_enabled = (scope.row.adv_enabled > 0 ? 0 : 1)
      save(data).then(() => {
        this.getTableData()
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the Advertising?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await del({ adv_id: row.adv_id })
          // baseAPI.get('user/witemplate/delete?id=' + row.id + '')
          this.tableList.splice($index, 1)
          this.getTableData()
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    openorderdetailsComp(scope) {
      this.$router.push({
        path: '/order/index',
        query: { id: scope.row.id }
      })
    },
    async confirm() {
      this.$refs.connectForm.validate(async valid => {
        if (valid) {
          const data = Object.assign({}, this.ad_info)
          if (this.ad_info.adv_startdate) {
            data.adv_startdate = parseTime(this.ad_info.adv_startdate, '{y}-{m}-{d}  {h}:{i}:{s}')
          }
          if (this.ad_info.adv_enddate) {
            data.adv_enddate = parseTime(this.ad_info.adv_enddate, '{y}-{m}-{d}  {h}:{i}:{s}')
          }
          if (!this.ad_info.adv_width) {
            data.adv_height = 0
          }
          if (!this.ad_info.adv_height) {
            data.adv_height = 0
          }
          await save(this.ad_info).then(async() => {
            this.dialogVisible = false
            await this.getTableData()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .icon-class {
    font-size: 20px;
  }
}
</style>

<style>
.table-info-row1 td {
      color: #03be1cef;
 }
.table-info-row2 td {
      color: #0057facb;
 }
.table-info-row3 td {
      color: #fd0000c5;
 }
.order-class .el-table .cell {
  white-space: pre-line !important;
}
.upload-demo .el-upload {
  width: 100%;
}
</style>
